package com.smy.realm;

import com.smy.pojo.Role;
import com.smy.pojo.User;
import com.smy.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author 史慕尧
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;


    /**
     * 认证方法
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user =(User) principalCollection.getPrimaryPrincipal();
        List<Role> roles = userService.queryUserHaveRole(user);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        try {
            if (roles!=null&&roles.size()>0){
                for (Role role : roles) {
                    info.addRole(role.getRoleDesc());
                }

            }
            return info;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 授权方法
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token =(UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        System.out.println("-----------------"+username);
        /**////验证登录信息
        User user = userService.login(username);
        if (user==null){return null;}
        String salt = user.getU1();

        return new SimpleAuthenticationInfo(user,user.getPassword(),new SimpleByteSource(salt),"myRealm");

    }


    public static void main(String[] args) {
        Md5Hash hash=new Md5Hash("123","2db7269b-9582-423d-9df5-63123d0f34a0",1024);
        System.out.println(hash);

    }
}
